<!-- 指标配置-卡片页 -->
<template>
  <view class="s-list">
    <Header title="指标配置" bgColor="#fff" :leftIconSize="20"/>
    <!-- 搜索 -->
    <view class="search-content">
      <view class="left">
        <uv-search placeholder="指标名称" bgColor="#fff" v-model="queryForm.name" :showAction="false" @change="searchList()" @clear="clear()"/>
      </view>
      <view class="screen-icon" @click="showPicker">
        <image v-if="iconFlag === true" src="@/static/image/index/icon2.png" mode="widthFix"/>
        <image v-else src="@/static/image/index/icon1.png" mode="widthFix"/>
      </view>
    </view>
    <view class='s-list-main'>
      <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered" :lower-threshold="50"
                   :style="{height: '100%'}" @scrolltolower="nextPage" :refresher-threshold="80"
                   refresher-background="rgb(244, 244, 244)" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                   @refresherrestore="onRestore" @refresherabort="onAbort">
        <view v-if="dataList.length > 0" class="indic-swipe">
          <uv-swipe-action>
            <uv-swipe-action-item v-for="(item,index) in dataList" :key="index" :options="options" @click="deconsteFun(item)">
              <view class="indic-box" @click="viewFun(item)">
                <view>
                  <view class='s-title'>{{ item.name }}</view>
                  <view class='s-row'>
                    <text>指标类型:</text>
                    <span v-if="item.entryType === '1' && tabType === 'law'">食品安全检查指标</span>
                    <span v-if="item.entryType === '2' && tabType === 'law'">校园安全检查指标</span>
                    <span v-if="item.entryType === '3' && tabType === 'law'">食堂自查指标</span>
                    <span v-if="item.entryType === '4' && tabType === 'law'">校园自查指标</span>
                    <span v-if="item.entryType === '5' && tabType === 'law'">配餐单位自查指标</span>
                    <span v-if="item.entryType === '6' && tabType === 'law'">配餐单位食品安全检查指标</span>
                    <span v-if="item.entryType === '7' && tabType === 'pco'">学校有害生物防治检查指标</span>
                    <span v-if="item.entryType === '8' && tabType === 'pco'">学校有害生物防治自查指标</span>
                  </view>
                  <view class='s-row'>
                    <text>更新时间:</text>
                    {{ proxy.dayjs(item.updateDate).format('YYYY-MM-DD') }}
                  </view>
                </view>
                <view class='s-btn-group'>
                  <!-- 选择学校 ，选择配餐单位公用页面-->
                  <view @click.stop="messageSelfTarget(item)" >
                    <uv-button  type="info" v-if="(item.entryType === '3' || item.entryType === '4' || item.entryType === '8') && item.publishFlag === 0"
                                plain text="下发通知" :disabled="!item.messageFlag" />
                  </view>
                  <uv-button type="info" v-if="item.publishFlag === 1 && (item.entryType === '3' || item.entryType === '4' || item.entryType === '8') " plain text="取消通知" @click="messageSelfTarget(item)"/>
                  <uv-button type="info" v-if="(item.entryType === '3' || item.entryType === '4' || item.entryType === '8') && item.publishFlag === 0" plain text="选择学校" @click="chooseOrg(item)"/>
                  <uv-button type="info" v-if="item.entryType === '5' && item.publishFlag === 0" plain text="选择配餐单位" @click="chooseOrg(item)"/>
                  <uv-button type="info" plain text="编辑" @click="updateFun(item)"/>
                </view>
              </view>
            </uv-swipe-action-item>
          </uv-swipe-action>
          <uni-load-more :status="loadingType" :content-text="contentText"/>
        </view>
        <view v-if="emptyFlag" class="empty-box">
          <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"/>
        </view>
      </scroll-view>
    </view>
    <!-- 底部按钮 -->
    <view class='s-btn-common'>
      <uv-button type="primary" text="添加" @click="addFun"/>
    </view>
    <!-- 筛选的下拉 -->
    <uv-action-sheet ref="searchPicker" title="筛选" :closeOnClickOverlay="false" :closeOnClickAction="false" @close="close">
      <slot>
        <view class="search-picker-main">
          <view v-for="(item,index) in searchColumns" :key="index" class="search-picker"
                :class="activeIndex===index?'search-picker-active':''" @click="pickerFun(item,index)">
            {{ item.name }}
          </view>
          <view class='s-btn-common'>
            <uv-button type="warning" text="重置" @click="resetFun()"/>
            <uv-button type="primary" text="确认" @click="screenFun()"/>
          </view>
        </view>
      </slot>
    </uv-action-sheet>
    <!-- 添加的弹层 -->
    <uv-popup ref="popup" @change="change">
      <view class="s-pop-main">
        <view class="close-view">
          <view class="title">请您选择添加指标类型</view>
          <uv-icon name="close" color="#333" size="20" @click="closePop"/>
        </view>
        <view class="s-pop-content">
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('1')">
            <image src="@/packageBase/static/image/food.png"/>
            <view class="content">食品安全检查指标</view>
          </view>
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('2')">
            <image src="@/packageBase/static/image/school.png"/>
            <view class="content">校园安全检查指标</view>
          </view>
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('3')">
            <image src="@/packageBase/static/image/canteen.png"/>
            <view class="content">食堂自查指标</view>
          </view>
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('4')">
            <image src="@/packageBase/static/image/campusSelf.png"/>
            <view class="content">校园自查指标</view>
          </view>
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('5')">
            <image src="@/packageBase/static/image/cateringSelf.png"/>
            <view class="content">配餐单位自查指标</view>
          </view>
          <view v-if="tabType === 'law'" class="s-pop-item" @click="goAddList('6')">
            <image src="@/packageBase/static/image/catering.png"/>
            <view class="content">配餐单位食品安全检查指标</view>
          </view>
          <view v-if="tabType === 'pco'" class="s-pop-item" @click="goAddList('7')">
            <image src="@/packageBase/static/image/school.png"/>
            <view class="content">学校有害生物防治检查指标</view>
          </view>
          <view v-if="tabType === 'pco'" class="s-pop-item" @click="goAddList('8')">
            <image src="@/packageBase/static/image/campusSelf.png"/>
            <view class="content">学校有害生物防治自查指标</view>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
  import targetAPI from '@/api/law/target/target';
  import {onLoad} from '@dcloudio/uni-app';
  import {reactive, ref, getCurrentInstance} from "vue";
  import config from "@/common/config";
  let imgMinioPath = ref(config.IMG_MINIO_PATH);
  const {proxy} = getCurrentInstance();
  const freshing = ref(false);
  const triggered = ref(false);
  const emptyFlag = ref(false);
  const loadingType = ref('noMore');
  const contentText = reactive({
    contentdown: "上拉显示更多",
    contentrefresh: "正在加载...",
    contentnomore: "没有更多数据了"
  });
  const options = ref([{
    text: '删除',
    style: {
      backgroundColor: '#f56c6c'
    }
  }]);

  let editFlag = ref(false);
  let iconFlag = ref(false);
  const total = ref(0);
  const dataList = reactive([]);
  let userInfo = ref(uni.getStorageSync('userInfo'));
  const queryForm = reactive({ // 查询条件
    pageSize: 10,
    pageNum: 1,
    entryType: '',
    createOrgId: userInfo.value.user.orgId,
  });
  let tabType = ref('law');

  /** 数据加载 */
  onLoad(async () => {
    initTabList();
    searchList();
  });

  // 初始化tab列表
  let initTabList = () => {
    userInfo.value.permissions.find(item => {
      if (item === 'iot:send:jyj') {
        tabType.value = 'pco';
        searchColumns.value = pcoSearchColumns.value;
      }
    })
  };

  /** 搜索数据列表 */
  let searchList = () => {
    queryForm.pageNum = 1;
    getListData();
  };

  /** 获取数据列表 */
  let getListData = async () => {
    let res = await proxy.http.asyncPost(targetAPI.targetPage, queryForm);
    if (res.code === 0) {
      total.value = res.data.total;
      if (queryForm.pageNum === 1) {
        dataList.length = 0;
      }
      dataList.push(...res.data.records);
      if (dataList.length < total.value) {
        loadingType.value = 'more';
      } else {
        loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
      }
      emptyFlag.value = dataList.length <= 0;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 筛选 */
  let searchColumns = ref([
    {
      id: '1',
      name: '食品安全检查指标',
    }, {
      id: '2',
      name: '校园安全检查指标',
    }, {
      id: '3',
      name: '食堂自查指标'
    }, {
      id: '4',
      name: '校园自查指标'
    }, {
      id: '5',
      name: '配餐单位自查指标'
    }, {
      id: '6',
      name: '配餐单位食品安全检查指标'
    },
  ]);

  let pcoSearchColumns = ref([
    {
      id: '7',
      name: '学校有害生物防治检查指标'
    }, {
      id: '8',
      name: '学校有害生物防治自查指标'
    }
  ]);

  const searchPicker = ref(); // 实例化
  let searchFlag = ref(true);
  let searchHistory = ref({
    activeIndex: '',
    entryType: ''
  });
  // 筛选-打开
  const showPicker = () => {
    searchPicker.value.open();
  };
  // 筛选-取消
  const close = () => {
    if (searchFlag.value) {
      activeIndex.value = searchHistory.value.activeIndex;
      queryForm.entryType = searchHistory.value.entryType;
    }
  };
  const activeIndex = ref('');
  // 筛选-点击
  const pickerFun = (item, index) => {
    iconFlag.value = true;
    activeIndex.value = index;
    queryForm.entryType = item.id;
  };
  // 筛选-确认
  const screenFun = () => {
    searchFlag.value = true;
    searchHistory.value = {
      entryType: queryForm.entryType,
      activeIndex: activeIndex.value
    };
    searchList();
    searchPicker.value.close();
  };
  // 筛选-重置
  const resetFun = () => {
    searchFlag.value = false;
    iconFlag.value = false;
    activeIndex.value = '';
    queryForm.entryType = '';
    searchList();
    searchPicker.value.close();
  };

  /** 清空条件 */
  let clear = () => {
    searchList();
  }

  /** 添加 */
  const popup = ref(); // 实例化
  // 打开选择指标类型弹窗
  const addFun = () => {
    popup.value.open('center');
  };
  // 关闭选择指标类型弹窗
  const closePop = () => {
    popup.value.close();
  };
  // 跳转新增页面
  const goAddList = (e) => {
    popup.value.close();
    uni.navigateTo({
      url: '/packageBase/pages/indicConfig/indicConfig-add?entryType=' + e,
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      }
    });
  };

  /** 编辑 */
  const updateFun = (item) => {
    editFlag.value = true;
    uni.navigateTo({
      url: '/packageBase/pages/indicConfig/indicConfig-add?row=' + encodeURIComponent(JSON.stringify(item)) + '&editFlag=' + true,
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      }
    });
  };
  /** 查看详情 */
  const viewFun = (item) => {
    if (!editFlag.value) {
      uni.navigateTo({
        url: '/packageBase/pages/indicConfig/indicConfig-view?row=' + encodeURIComponent(JSON.stringify(item)),
      });
    }
    editFlag.value = false;
  };

  /** 配置机构 */
  const chooseOrg = (e) => {
    editFlag.value = true;
    uni.navigateTo({
      url: '/packageBase/pages/indicConfig/indicConfig-school?entryType=' + e.entryType + '&rowId=' + e.id,
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      }
    });
  };

  /** 通知or取消通知 */
  const messageSelfTarget = async (item) => {
    if (item.messageFlag){
      editFlag.value = true;
      let query = {
        id: item.id,
        name: item.name,
        publishFlag: item.publishFlag === 1 ? 0 : 1
      }
      let res = await proxy.http.asyncPost(targetAPI.messageSelfTarget, query);
      if (res.code === 0) {
        await uni.showToast({icon: 'success', title: '通知成功', duration: 2000});
        setTimeout(function() {
          searchList();
        }, 2000);
      }
    }
  }

  /** 删除 */
  const deconsteFun = (e) => {
    uni.showModal({
      title: '提示',
      // 提示文字
      content: '确认删除该条指标？',
      // 取消按钮的文字自定义
      cancelText: "取消",
      // 确认按钮的文字自定义
      confirmText: "删除",
      //删除字体的颜色
      confirmColor: 'red',
      //取消字体的颜色
      cancelColor: '#000000',
      success: async function (res) {
        if (res.confirm) {
          let res = await proxy.http.asyncPost(targetAPI.targetRemove(e.id));
          if (res.code === 0) {
            await uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {
              getListData();
            }, 1000);
          } else {
            await uni.showToast({title: res.msg, icon: 'none'});
          }
        } else {
          // 执行取消后的操作
        }
      }
    })
  };

  /** 滚动视图区域 */
  // 翻页
  let nextPage = () => {
    if (queryForm.pageNum * queryForm.pageSize < total.value) {
      queryForm.pageNum++;
      getListData()
    }
  }
  // 下拉
  let onPulling = () => {
    freshing.value = false;
    setTimeout(() => {
      triggered.value = true;
    }, 1000)
  };
  // 刷新
  let onRefresh = () => {
    if (freshing.value) return;
    triggered.value = 'restore';
    setTimeout(() => {
      freshing.value = false;
      triggered.value = false;
    }, 1000)
    //获取数据的函数
    queryForm.pageNum = 1 // 记录数
    getListData()
  };
  let onRestore = () => {
    triggered.value = 'restore'; // 需要重置
  };
  let onAbort = () => {
    console.log("onAbort");
  };
</script>

<style scoped lang="scss">
  ::v-deep .indic-box .s-btn-group .uv-button--plain.uv-button--info {
    color: #000000 !important;
  }
  .search-icon{
    width: 60rpx !important;
    height: 60rpx !important;
  }
  .s-pop-item{
    image{
      width: 40px !important;
      height: 40px !important;
    }
  }
  ::v-deep {
    .uv-button--disabled {
      pointer-events: auto;
    }
  }
</style>
